<?php

namespace ASW\Communication\Rdc;


use ArrayObject;
use ASW\Utility\ExecuteResult;

class RdcServerCommand extends RdcServerFrame
{
    /**
     * 客户端回复指令时使用的请求指令名
     */
    const REPLY_ACTION = "command_reply";

    /**
     * 客户端回复指令时参数中表示下发指令序列号的参数名
     */
    const REPLY_ARG_SEQ = "command_seq";

    /**
     * 客户端回复指令时参数中表示指令执行结果的参数名
     */
    const REPLY_ARG_RESULT = "execute_result";

    private static int $baseSeq = 0;

    public string $action = '';

    public array|ArrayObject $args;

    private function __construct()
    {
        $this->args = new ArrayObject();
    }

    public function makeReplyRequest(ExecuteResult $result): RdcClientRequest
    {
        $request                                 = RdcClientRequest::create(static::REPLY_ACTION);
        $request->args[static::REPLY_ARG_SEQ]    = $this->seq;
        $request->args[static::REPLY_ARG_RESULT] = $result;

        return $request;
    }

    public static function fromArray(array $array): static
    {
        $instance         = new static();
        $instance->type   = RdcServerFrameType::Command;
        $instance->seq    = $array['seq'] ?? 0;
        $instance->action = $array['action'] ?? 0;
        $instance->args   = $array['args'];
        return $instance;
    }

    public static function create(string $action, array|null $args = null): static
    {
        $instance         = new static();
        $instance->type   = RdcServerFrameType::Command;
        $instance->seq    = ++static::$baseSeq;
        $instance->action = $action;
        $instance->args   = $args === null || count($args) == 0 ? new ArrayObject() : $args;
        return $instance;
    }
}